﻿using System.Linq;
using ISSMoviePlex.DAL.Models;
using WebMatrix.WebData;
using System.Web.Security;

namespace ISSMoviePlex.DAL.Repositories
{
    public class AccountRepository : BaseRepository<int, UserProfile, AccountRepository>
    {
        public AccountRepository()
        {
            if (!WebSecurity.Initialized)
            {
                WebSecurity.InitializeDatabaseConnection(CONNECTION_STRING, "System.Data.SqlClient", "UserProfile", "UserId", "UserName", autoCreateTables: true);
            }
        }

        public bool ServiceLogin(LoginModel model)
        {
            var user = Context.UserProfiles.FirstOrDefault(u => u.UserName.Equals(model.UserName));
            return user != null;
        }

        public bool Login(LoginModel model)
        {
            return WebSecurity.Login(model.UserName, model.Password, persistCookie: model.RememberMe);
        }        

        public void Logout()
        {
            WebSecurity.Logout();
        }

        public int Register(RegisterModel model)
        {
            WebSecurity.CreateUserAndAccount(model.UserName, model.Password, new { Status = true });
            WebSecurity.Login(model.UserName, model.Password);
            Roles.AddUserToRole(model.UserName, "Member");
            return WebSecurity.GetUserId(model.UserName);
        }

        public bool ChangePassword(string userName, LocalPasswordModel model)
        {
            return WebSecurity.ChangePassword(userName, model.OldPassword, model.NewPassword);
        }

        public UserProfile GetUser(int id)
        {
            return Context.UserProfiles.SingleOrDefault(u => u.UserId == id);
        }

        public UserProfile GetUser(string userName)
        {
            return Context.UserProfiles.SingleOrDefault(u => u.UserName == userName);
        }

        public override UserProfile FindById(int id)
        {
            return Context.UserProfiles.SingleOrDefault(u => u.UserId == id);
        }
        public int GetCurrentUserId()
        {
            return WebSecurity.CurrentUserId;
        }
    }
}
